import router from '@/router/index';
import store from '@/store'
import asyncRoutes from '@/router/asyncRoutes'

const whiteList = ['/login', '/404'];


// 获取一级权限的标识
function getFirstRoutePermission(permission) {
    const firstArr = permission.map(item => {
        return item.split(':')[0]
    })
    // 去重 set不能存重复的数据（去重）不是一个真实的数组
    return Array.from(new Set(firstArr));
}

// 获取二级权限的标识
function getSecondRoutePermission(permission) {
    const secondArr = permission.map(item => {
        const arr = item.split(':')
        return `${arr[0]}:${arr[1]}`
    })
    return Array.from(new Set(secondArr));
}

// 根据一级二级权限标识，筛选出对应可展示的动态路由
function getRoutes(firstPermission, secondPermission, asyncRoutes) {
    // 判断当前登录人是不是管理员,如果是管理员就不进行筛选
    if (firstPermission.includes('*')) {
        return asyncRoutes;
    }
    const firstRoutes = asyncRoutes.filter(item => firstPermission.includes(item.permission))
    // console.log('一级动态路由', firstRoutes);
    // 对筛选后的一级路由进行二级路由的筛选
    const routes = firstRoutes.map(item => {
        return {
            ...item,
            children: item.children.filter(child => secondPermission.includes(child.permission))
        }
    })
    return routes;
}

router.beforeEach(async (to, from, next) => {
    // to:跳转的路由对象
    // from: 从哪里来
    //next:放行
    const token = store.state.user.token;
    if (token) {
        if (to.path === '/login') {
            next('/')
        } else {
            next();
            // 1.拿到用户的权限信息
            const permission = await store.dispatch('menu/getUserPermission');
            // 2.根据权限标识，筛出对应的一级路由
            const firstPermission = getFirstRoutePermission(permission);
            // 3.根据权限标识 筛出对应的二级路由标识
            const secondPermission = getSecondRoutePermission(permission);
            // 4.根据一级权限标识和二级权限标识和动态路由进行筛选
            const routes = getRoutes(firstPermission, secondPermission, asyncRoutes)
            // 5.把筛选后的路由展示在菜单栏（跳转）
            routes.forEach(item => router.addRoute(item))
            // 6.把筛选后的路由存放进vuex（渲染）
            store.commit('menu/setMenuList', routes);
        }
    } else {
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }
    next()
})